//
//  THUIAlertView.m
//  MengLiao
//
//  Created by xiuxin on 2022/7/15.
//  Copyright © 2022 BaseBusiness. All rights reserved.
//
#import "THUIAlertView.h"

#define THUIAlertViewWidth               KRelative(540) //弹窗宽度
#define THUIAlertViewContentMargin       KRelative(30) //内容距离边框间距
#define THUIAlertViewTopMargin           KRelative(20)    //顶部间距
#define THUIAlertViewTitleHeight         KRelative(40) //标题高度
#define THUIAlertViewBtnHeight           KRelative(60) //按钮高度
#define THUIAlertViewBtnBottomMargin     KRelative(30) //按钮底部间距
#define THUIAlertViewMaxContentHeight    (kMainScreenHeight * 0.35)
#define THUIAlertViewButtonMargin        KRelative(40)
@implementation HQUIAlertData

- (id)initWithTitle:(NSString *)title message:(NSString *)message leftBtnTitle:(NSString *)leftBtnTitle rightBtnTitle:(NSString *)rightBtnTitle handler:(THUIAlertViewHandler)handler
{
    self = [super init];
    _title = title;
    _content = message;
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:2];
    if (leftBtnTitle.length > 0)
    {
        [array addObject:leftBtnTitle];
    }
    if (rightBtnTitle.length > 0)
    {
        [array addObject:rightBtnTitle];
    }
    if (array.count > 0)
    {
        _btnTitleArray = array;
    }
    _handler = handler;
    return self;
}

- (id)initWithTitle:(NSString *)title attributedString:(NSAttributedString *)message leftBtnTitle:(NSString *)leftBtnTitle rightBtnTitle:(NSString *)rightBtnTitle handler:(THUIAlertViewHandler)handler
{
    self = [super init];
    _title = title;
    _contentAttributedString = message;
    NSMutableArray * array = [NSMutableArray arrayWithCapacity:2];
    if (leftBtnTitle.length > 0)
    {
        [array addObject:leftBtnTitle];
    }
    if (rightBtnTitle.length > 0)
    {
        [array addObject:rightBtnTitle];
    }
    if (array.count > 0)
    {
        _btnTitleArray = array;
    }
    _handler = handler;
    return self;
}

@end

@interface THUIAlertView()

@property (strong,nonatomic) UIView * contentView;

@property (strong,nonatomic) UIScrollView * contentScrollView;

@property (nonatomic) CGSize contentSize;

@end

@implementation THUIAlertView

+ (THUIAlertView *)getInstance
{
    return [self new];
}

- (id)init
{
    self = [super init];
    [self createUI];
    _dismissOnClickDimView = NO;
    _windowPriority = HQWindowViewPriorityHigh;
    return self;
}

- (void)createUI
{
    self.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.3];
    _contentView = [UIView new];
    _contentView.backgroundColor = [UIColor whiteColor];
    _contentView.layer.cornerRadius = KRelative(20.0f);
    _contentView.layer.masksToBounds = YES;
    _contentView.userInteractionEnabled = YES;
    [self addSubview:_contentView];
    _titleLabel = [UILabel new];
    [_titleLabel setTextColor:Color_text_33];
    [_titleLabel setFont:kFontMedium(KRelative(32))];
    [self.contentView addSubview:_titleLabel];
    
    _contentScrollView = [UIScrollView new];
    _contentScrollView.backgroundColor = [UIColor clearColor];
    _contentScrollView.bounces = NO;
    [self.contentView addSubview:_contentScrollView];
    _contentLabel = [YYLabel new];
    _contentLabel.textAlignment = NSTextAlignmentCenter;
    [_contentLabel setNumberOfLines:0];
    _contentLabel.preferredMaxLayoutWidth = THUIAlertViewWidth - THUIAlertViewContentMargin * 2;
    [_contentScrollView addSubview:_contentLabel];
    
    [self createBtn];
}

- (void)createBtn
{
    _leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_leftBtn setAdjustsImageWhenHighlighted:NO];
    [_leftBtn setBackgroundColor:[UIColor whiteColor]];
    [_leftBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_leftBtn setContentEdgeInsets:UIEdgeInsetsMake(0, KRelative(20), 0, KRelative(20))];
    _leftBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _leftBtn.layer.allowsEdgeAntialiasing = YES;
    _leftBtn.layer.borderWidth = KLineHeight;
    _leftBtn.layer.cornerRadius = THUIAlertViewBtnHeight/2;
    [_leftBtn.titleLabel setFont:kFontRegular(KRelative(30))];
    _leftBtn.layer.borderColor = [ColorFromHex(0xdedede) CGColor];
    [_leftBtn setTitleColor:Color_text_99 forState:UIControlStateNormal];
    
    _rightBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [_rightBtn setAdjustsImageWhenHighlighted:NO];
    [_rightBtn addTarget:self action:@selector(btnClicked:) forControlEvents:UIControlEventTouchUpInside];
    [_rightBtn setContentEdgeInsets:UIEdgeInsetsMake(0, KRelative(20), 0, KRelative(20))];
    _rightBtn.titleLabel.adjustsFontSizeToFitWidth = YES;
    _rightBtn.layer.allowsEdgeAntialiasing = YES;
    _rightBtn.layer.cornerRadius = THUIAlertViewBtnHeight/2;
    [_rightBtn.titleLabel setFont:kFontRegular(KRelative(30))];
    _rightBtn.backgroundColor = kThemeColor;
    [_rightBtn setTitleColor:Color_text_33 forState:UIControlStateNormal];
    
    _leftBtn.tag = 0;
    [self.contentView addSubview:_leftBtn];
    
    _rightBtn.tag = 1;
    [self.contentView addSubview:_rightBtn];
    

}

- (void)updateDisplay
{
//    if (_alertData.title.length > 0)
//    {
//        [_contentLabel setFont:kFontRegular(KRelative(26))];
//        [_contentLabel setTextColor:Color_text_66];
//    }
//    else
//    {
//        [_contentLabel setFont:kFontRegular(KRelative(28))];
//        [_contentLabel setTextColor:ColorFromHex(0x262626)];
//    }
    
    if (_alertData.content.length == 0 && _alertData.contentAttributedString.length == 0)
    {
        _contentSize = CGSizeZero;
    }
    else if(_alertData.content.length > 0)
    {
        NSMutableAttributedString *text = [[NSMutableAttributedString alloc] initWithString:_alertData.content];
        text.yy_font = _contentLabel.font;
        YYTextContainer *container = [YYTextContainer new];
        container.size = CGSizeMake(THUIAlertViewWidth - THUIAlertViewContentMargin * 2, MAXFLOAT);
        container.maximumNumberOfRows = 0;
        YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:text];
        _contentSize = layout.textBoundingSize;
    }
    else if(_alertData.contentAttributedString.length > 0)
    {
        YYTextContainer *container = [YYTextContainer new];
        container.size = CGSizeMake(THUIAlertViewWidth - THUIAlertViewContentMargin * 2, MAXFLOAT);
        container.maximumNumberOfRows = 0;
        YYTextLayout *layout = [YYTextLayout layoutWithContainer:container text:_alertData.contentAttributedString];
        _contentSize = layout.textBoundingSize;
    }
    
    _contentScrollView.scrollEnabled = _contentSize.height > THUIAlertViewMaxContentHeight;
    _contentScrollView.bounces = _contentScrollView.scrollEnabled;
    _contentScrollView.contentSize = _contentSize;
    [self createViewLayouts];
    [self layoutIfNeeded];
}

- (void)btnClicked:(UIButton *)btn
{
    if (_alertData.handler)
    {
        _alertData.handler(btn.tag);
    }
    [self dismiss];
}

- (void)createViewLayouts
{
    CGFloat contentBottom = -THUIAlertViewBtnBottomMargin;
    if (_alertData.btnTitleArray.count > 0)
    {
        contentBottom = -THUIAlertViewBtnBottomMargin - THUIAlertViewBtnHeight - KRelative(30);
    }
    
    [self.titleLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(0));
        make.left.equalTo(@(THUIAlertViewContentMargin));
        make.top.equalTo(@(THUIAlertViewTopMargin));
    }];

    [_contentScrollView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(0));
        make.left.equalTo(@(THUIAlertViewContentMargin));
        make.height.equalTo(@(MIN(THUIAlertViewMaxContentHeight, _contentSize.height)));
        make.top.equalTo(@(self.alertData.title.length > 0 ? KRelative(86) : KRelative(20)));
        make.bottom.equalTo(@(contentBottom));
    }];
    
    [_contentLabel mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.top.equalTo(@(0));
        make.width.equalTo(@(THUIAlertViewWidth - THUIAlertViewContentMargin * 2));
        make.height.equalTo(@(self.contentSize.height));
    }];
    
    [self updateButtonLayout];
    
    [self.contentView mas_updateConstraints:^(MASConstraintMaker *make) {
        make.centerX.equalTo(@(0));
        make.centerY.equalTo(self.mas_top).offset(kMainScreenHeight / 2);
        make.width.equalTo(@(THUIAlertViewWidth));
    }];
}

- (void)updateButtonLayout
{
    if (self.alertData.btnTitleArray.count > 1) {
        CGFloat buttonWidth = (THUIAlertViewWidth - THUIAlertViewButtonMargin * 3) / 2;
        [self.leftBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(buttonWidth));
            make.bottom.equalTo(@(-THUIAlertViewBtnBottomMargin));
            make.left.equalTo(@(THUIAlertViewButtonMargin));
            make.height.equalTo(@(THUIAlertViewBtnHeight));
        }];
        
        [self.rightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(buttonWidth));
            make.bottom.equalTo(@(-THUIAlertViewBtnBottomMargin));
            make.right.equalTo(@(-THUIAlertViewButtonMargin));
            make.height.equalTo(@(THUIAlertViewBtnHeight));
        }];
    }else{
        [self.rightBtn mas_updateConstraints:^(MASConstraintMaker *make) {
            make.width.equalTo(@(THUIAlertViewWidth - THUIAlertViewButtonMargin * 2));
            make.bottom.equalTo(@(-THUIAlertViewBtnBottomMargin));
            make.right.equalTo(@(-THUIAlertViewButtonMargin));
            make.height.equalTo(@(THUIAlertViewBtnHeight));
        }];
    }
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    if ([touches anyObject].view == self.contentView) {
        return;
    }
    if (self.dismissOnClickDimView) {
        [self dismiss];
    }
}

- (void)loadAlertData:(HQUIAlertData *)alertData
{
    _alertData = alertData;
    _titleLabel.text = alertData.title;
    _titleLabel.hidden = alertData.title.length == 0;
    _titleLabel.textAlignment = NSTextAlignmentCenter;

    if (alertData.content.length > 0) {
        _contentLabel.text = alertData.content;
    }else if (alertData.contentAttributedString.length > 0){
        _contentLabel.attributedText = alertData.contentAttributedString;
    }
    
    _contentLabel.hidden = alertData.content.length == 0 && alertData.contentAttributedString.length == 0;
    
    _rightBtn.hidden = alertData.btnTitleArray.count == 0;
    if (alertData.btnTitleArray.count > 1)
    {
        [_leftBtn setTitle:[alertData.btnTitleArray firstObject] forState:UIControlStateNormal];
    }
    _leftBtn.hidden = alertData.btnTitleArray.count < 2;
    if (alertData.btnTitleArray.count > 0)
    {
        [_rightBtn setTitle:[alertData.btnTitleArray lastObject] forState:UIControlStateNormal];
    }
    
    if (alertData.btnTitleArray.count == 0)
    {
        _dismissOnClickDimView = YES;
    }
    
    [self updateDisplay];
    
}

- (void)show
{
    if (![THWindowPriority requestPriority:self.windowPriority view:self])
    {
        return;
    }

    for (THUIAlertView * view in [UIApplication sharedApplication].keyWindow.subviews)
    {
        if ([view isKindOfClass:[THUIAlertView class]])
        {
            [view removeFromSuperview];
        }
    }
    
    if (_alertData.title.length <= 0 && _alertData.content.length <= 0 && _alertData.contentAttributedString.length <= 0 && _alertData.btnTitleArray.count <= 0) {
        return;
    }
    
    
    [[UIApplication sharedApplication].keyWindow addSubview:self];
    [self mas_updateConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(@(0));
    }];

    [self updateConstraints];
    [self layoutIfNeeded];
    CAKeyframeAnimation *animation = [CAKeyframeAnimation animationWithKeyPath:@"transform.scale"];
    animation.values = @[@(0.8), @(1.05), @(1.1), @(1)];
    animation.keyTimes = @[@(0), @(0.3), @(0.5), @(1.0)];
    animation.timingFunctions = @[[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear], [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionLinear]];
    animation.duration = .28;
    [self.contentView.layer addAnimation:animation forKey:@"bounce"];
}

- (void)dismiss
{
    CGFloat offset = 0.0f;
    if ([self.contentView.layer animationForKey:@"bounce"]) {
        offset = 0.3f;
    }
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(offset * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [THWindowPriority releasePriority:self.windowPriority view:self];
        self.userInteractionEnabled = NO;
        [UIView animateWithDuration:.3 animations:^{
            [self endEditing:YES];
            self.alpha = 0;
            self.contentView.transform = CGAffineTransformMakeScale(.4, .4);
        }completion:^(BOOL finished) {
            [self removeFromSuperview];
        }];
    });
}

- (void)setHandler:(THUIAlertViewHandler)handler
{
    _alertData.handler = handler;
}

+ (THUIAlertView *)alertWithTitle:(NSString *)title message:(NSString *)message leftBtn:(NSString *)leftTitle rightBtn:(NSString *)rightTitle handler:(THUIAlertViewHandler)handler
{
    THUIAlertView * alert = [THUIAlertView getInstance];
    [alert loadAlertData:[[HQUIAlertData alloc] initWithTitle:title message:message leftBtnTitle:leftTitle rightBtnTitle:rightTitle handler:handler]];
    return alert;
}

+ (THUIAlertView *)alertWithTitle:(NSString *)title attributedString:(NSAttributedString *)message leftBtn:(NSString *)leftTitle rightBtn:(NSString *)rightTitle handler:(THUIAlertViewHandler)handler
{
    THUIAlertView * alert = [THUIAlertView getInstance];
    [alert loadAlertData:[[HQUIAlertData alloc] initWithTitle:title attributedString:message leftBtnTitle:leftTitle rightBtnTitle:rightTitle handler:handler]];
    return alert;
}


@end
